<template>
  <view>
    <!-- 余额总览 -->
    <view class="m-3 b-d">
      <view class="balance-card  p-4 pb-1 rounded20 d-flex d-flex-column">
        <text>当前余额</text>
        <text class="py-1">¥
          <text class="ml-1 amount colorfff">{{ walletForm.balance }}</text>
        </text>
        <view class="d-flex py-2 bBottom d-flex-between mt-5">
          <view>可提现余额</view>
          <view>{{ walletForm.agent_balance }}</view>
        </view>
      </view>
      <view class="wBottom">
        <view class="d-flex py-2 bBottom  d-flex-around ">
          <view class="d-flex d-flex-middle colorfc7608" @click="goUrl('/subPages/recharge/recharge')">
            <text class="iconfont icon-chongzhi font38"></text>
            充值
          </view>
        </view>
      </view>
    </view>

    <!-- 时间筛选 -->
    <view class="filter m-2 d-flex d-flex-middle d-flex-between mt-5">
      <text class="font32 font-bold">余额明细</text>
      <picker mode="date" @change="startDateChange" :value="startDate" v-if="!startDate">
        <text class="font22 ">开始时间</text>
        <text class="color999 ml-1 iconfont icon-xiajiantou font22"></text>
      </picker>
      <picker mode="date" @change="endDateChange" :value="endDate" v-else-if="!endDate">
        <text class="font22 ">结束时间</text>
        <text class="color999 ml-1 iconfont icon-xiajiantou font22"></text>
      </picker>
      <view v-else @click="resetDateRange" class="date-range-display">
        <text class="font22 ">{{ startDate }} 至 {{ endDate }}</text>
        <text class="color999 ml-1 iconfont icon-xiajiantou font22"></text>
      </view>
    </view>

    <!-- 交易列表 -->
    <scroll-view
        scroll-y
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        class="scroll-area"
        style="height: calc(100vh - 600rpx);"
    >
      <!-- 下拉刷新提示 -->
      <view class="refresh-tip" v-if="refreshing">
        <text class="iconfont icon-loading font28"></text>
        <text class="ml-1">正在刷新...</text>
      </view>

      <view v-for="(item,index) in walletForm.data" :key="index" class="record-item d-flex-middle mx-3 py-3">
        <view class="d-flex d-flex-column">
          <text>{{ item.remark }}</text>
          <text class="time font22 color999 mt-1">{{ item.updated_at }}</text>
        </view>
        <text :class="item.amount > 0 ? 'income' : 'expense'">
         {{ item.amount }}
        </text>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-more text-center py-3" v-if="loadingMore">
        <text class="font24 color999">加载中...</text>
      </view>
      <view class="loading-more text-center py-3" v-else-if="noMoreData">
        <text class="font24 color999">没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>


<script>
import {
  mapState
} from "vuex"
import {
  userApi,
} from "@/http/userApi"

export default {
  data() {
    return {
      currentDate: '2025-07-15',
      list: [{
        type: '提现',
        time: '2022.11.30 08:30:10',
        amount: 50
      }],
      walletForm: {
        balance: 0,
        agent_balance: 0,
        data: []
      },
      refreshing: false, // 下拉刷新状态
      loadingMore: false, // 加载更多状态
      noMoreData: false, // 没有更多数据
      page: 1, // 当前页码
      startDate:'',
      endDate:''
    }
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
    })
  },
  onLoad() {
    this.initWallet()
  },
  methods: {
    async initWallet() {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '加载中...'
        });

        let params = {
          page: this.page,
          start_time: this.startDate,
          end_time: this.endDate
        };

        let res = await userApi.getWallet(params);
        this.walletForm = res;

        // 处理分页相关状态
        if (res.data && Array.isArray(res.data)) {
          // 如果是第一页，直接赋值；否则追加数据
          if (this.page === 1) {
            this.walletForm.data = res.data;
          } else {
            this.walletForm.data = [...this.walletForm.data, ...res.data];
          }

          // 根据返回的数据判断是否还有更多数据
          this.noMoreData = res.data.length === 0 || res.data.length < 10; // 假设每页10条
        }

        // 隐藏加载提示
        uni.hideLoading();
      } catch (error) {
        // 隐藏加载提示
        uni.hideLoading();

        uni.showToast({
          title: '获取钱包信息失败',
          icon: 'none'
        });

        // 输出错误信息到控制台，便于调试
        console.error('获取钱包信息失败:', error);
      }
    },

    // 下拉刷新
    async onRefresh() {
      if (this.refreshing) return;

      this.refreshing = true;
      this.page = 1;

      try {
        // 重新获取钱包信息
        await this.initWallet();

        uni.showToast({
          title: '刷新成功',
          icon: 'success'
        });
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        this.refreshing = false;
      }
    },

    // 加载更多
    async loadMore() {
      if (this.loadingMore || this.noMoreData || this.refreshing) return;

      this.loadingMore = true;
      this.page++;

      try {

        setTimeout(() => {
          this.loadingMore = false;
        }, 1000);

      } catch (error) {
        this.page--;
        this.loadingMore = false;
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    },

    startDateChange(e) {
      this.startDate = e.detail.value;
    },

    endDateChange(e) {
      this.endDate = e.detail.value;

      // 验证结束时间不能早于开始时间
      if (this.startDate && this.endDate) {
        const startDateObj = new Date(this.startDate);
        const endDateObj = new Date(this.endDate);

        if (endDateObj < startDateObj) {
          uni.showToast({
            title: '结束时间不能早于开始时间',
            icon: 'none'
          });
          this.endDate = '';
          return;
        }

        // 重新加载数据
        this.onRefresh();
      }
    },

    resetDateRange() {
      this.startDate = '';
      this.endDate = '';
      // 重新加载数据
      this.onRefresh();
    },

    goUrl(urlPages) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
      } else {
        uni.navigateTo({
          url: urlPages
        });
      }
    }
  }
}
</script>

<style>
.balance-card {
  background: linear-gradient(90deg, #feb50f, #fc7608);
  color: white;
}

.colorfc7608 {
  color: #fc7608;
}

.color7ac0d9 {
  color: #6bd0e0;
}

.bBottom {
  border-top: 1rpx solid rgba(255, 255, 255, .5);
}

.record-item {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
}

.income {
  color: #4CAF50;
}

.expense {
  color: #F44336;
}

.b-d {
  background-color: #f8f8f8;
}

.amount {
  font-size: 60rpx;
}

.wBottom {
  position: relative;
}

.scroll-area {
  height: calc(100vh - 300rpx);
}

.refresh-tip {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
}

.loading-more {
  text-align: center;
}

.icon-loading {
  display: inline-block;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.time {
  font-size: 22rpx;
}

.text-center {
  text-align: center;
}

.py-3 {
  padding-top: 30rpx;
  padding-bottom: 30rpx;
}

.font24 {
  font-size: 24rpx;
}
</style>